<template>
  <backContainer>

    <div class="box">

      <card height="100%" class="questioncard">
        <div class="submited_text submited_state_top bg_color_red">
          {{ anonymousFlag == 1 ? '本问卷为匿名问卷' : '本问卷为实名问卷' }}
        </div>
        <div class="center" v-if="markStatus == 0">
          <div class="computertitle">
            <div style="font-weight: bold">{{ surveyName }}</div>
            <div class="computertext" v-html="surveyDescription"></div>
          </div>

          <!-- 试题 -->
          <div class="computerquestions">
            <div v-for="(item, answerIndex) in answerList" :key="answerIndex">
              <div
                v-if="item.questionType !== 3"
                :class="
                  item.requiredFlag == 1
                    ? 'required itemtitle'
                    : 'itemtitle titspace'
                "
              >
                <span>{{ answerIndex + 1 }}、</span>
                <span
                  v-html="item.questionName"
                  style="display: flex"
                  @click="showImg($event)"
                ></span>
                <span style="margin-left: 10px">
                  <el-tag type="success">{{
                      typeList[item.questionType - 1]
                    }}</el-tag>
                </span>
              </div>
              <div v-else class="multTitle">
                <div class="gapFill">
                  <div
                    :class="
                      item.requiredFlag == 1
                        ? 'required itemtitle'
                        : 'itemtitle titspace'
                    "
                  >
                    {{ answerIndex + 1 }}、
                  </div>
                  <div style="display: flex; flex-wrap: wrap">
                    <div
                      v-for="(o, i) of item.questionNameList"
                      :key="i"
                      style="display: flex; align-items: center"
                    >
                      <div
                        v-if="o.name != '</p>'"
                        style="display: flex; align-items: center"
                      >
                        <span v-html="o.name" @click="showImg($event)"></span>
                        <el-input
                          v-if="i != item.questionNameList.length - 1"
                          v-model="o.value"
                          placeholder="请输入内容"
                          style="
                            width: 120px;
                            margin-left: 5px;
                            margin-right: 10px;
                          "
                        ></el-input>
                      </div>
                    </div>
                    <span style="margin-left: 10px">
                      <el-tag type="success">{{
                          typeList[item.questionType - 1]
                        }}</el-tag>
                    </span>
                  </div>
                </div>
              </div>
              <div
                v-if="item.questionDescription"
                style="padding-left: 35px; font-size: 12px; color: #ddd"
              >
                {{ item.questionDescription }}
              </div>
              <!-- 单选选择题 -->
              <div v-if="item.questionType == 1">
                <div v-for="(e, index) in item.optionList" :key="index">
                  <div class="flleft">
                    <div @click.prevent="radioClick(answerIndex, e)" style="margin-right: 20px">
                      <el-radio v-model="item.optionId" :label="e.id" :key="e.id" @click.native.prevent="optionIdradiochange(answerIndex)">
                        {{ e.optionName }}
                      </el-radio>
                    </div>


                    <div
                      :class="e.requiredFlag ? 'required fl' : 'fl'"
                      v-if="e.fillFlag == 1 && item.optionId == e.id"
                    >
                      <el-input
                        @input="inputchange($event)"
                        v-model="item.answerContent"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>
                  <div style="padding-left: 40px">
                    <img
                      :src="e.optionPicUrl"
                      alt="加载失败"
                      v-if="e.optionPicUrl"
                      style="width: 40px"
                    />
                  </div>
                </div>
              </div>
              <!-- 多选选择题 -->
              <div v-if="item.questionType == 2">
                <div v-for="(e, index) in item.optionList" :key="index">
                  <div class="flleft">
                    <el-checkbox
                      :true-label="e.id"
                      v-model="item.options[index].optionId"
                      @change="optionIdchange(answerIndex,index)"
                    >{{ e.optionName }}
                    </el-checkbox>

                    <div
                      :class="e.requiredFlag ? 'required fl mr' : 'fl mr'"
                      v-if="
                        e.fillFlag == 1 && item.options[index].optionId == e.id
                      "
                    >
                      <el-input
                        v-model="item.options[index].answerContent"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>

                  <div style="padding-left: 40px">
                    <img
                      :src="e.optionPicUrl"
                      alt="加载失败"
                      v-if="e.optionPicUrl"
                      style="width: 40px"
                    />
                  </div>
                </div>
              </div>
              <!-- 简答题 -->
              <div
                v-if="item.questionType == 4"
                style="margin-left: 20px; margin-top: 10px"
              >
                <el-input
                  type="textarea"
                  size="mini"
                  v-model="item.answerContent"
                  placeholder="请输入内容"
                ></el-input>
              </div>
            </div>
          </div>
          <div style="padding-left: 80px">
            <el-button type="primary" @click="submit" style="width: 10%"
            >提交
            </el-button>
          </div>
        </div>
        <div v-if="markStatus == 1" class="center">
          <div class="computertitle">
            <h1 style="color: rgba(39, 196, 120, 1)">{{ surveyName }}</h1>
            <div class="computertext" v-html="surveyDescription"></div>
          </div>
          <!-- 试题 -->
          <div class="computerquestions">
            <div v-for="(item, index) in answerList" :key="index">
              <div
                v-if="item.questionType !== 3"
                :class="
                  item.requiredFlag == 1
                    ? 'required itemtitle'
                    : 'itemtitle titspace'
                "
              >
                <span>{{ index + 1 }}、</span>
                <span v-html="item.questionName" style="display: flex" @click="showImg($event)"></span>
                <span style="margin-left: 10px">
                  <el-tag type="success">{{
                      typeList[item.questionType - 1]
                    }}</el-tag>
                </span>
              </div>
              <!-- 填空题 -->
              <div v-else class="multTitle">
                <div class="gapFill">
                  <div
                    :class="
                      item.requiredFlag == 1
                        ? 'required itemtitle'
                        : 'itemtitle titspace'
                    "
                  >
                    {{ index + 1 }}、
                  </div>
                  <div style="display: flex; flex-wrap: wrap">
                    <div
                      v-for="(o, i) of item.questionNameList"
                      :key="i"
                      style="display: flex; align-items: center"
                    >
                      <div
                        v-if="o.name != '</p>'"
                        style="display: flex; align-items: center"
                      >
                        <span v-html="o.name" @click="showImg($event)"></span>
                        <el-input
                          v-if="i != item.questionNameList.length - 1"
                          disabled
                          v-model="
                            JSON.parse(
                              item.answerMap[`questionId:${item.id}`]
                                .answerContent
                            )[i]
                          "
                          placeholder="请输入内容"
                          style="
                            width: 120px;
                            margin-left: 5px;
                            margin-right: 10px;
                          "
                        ></el-input>
                      </div>
                    </div>
                    <span style="margin-left: 10px">
                      <el-tag type="success">{{
                          typeList[item.questionType - 1]
                        }}</el-tag>
                    </span>
                  </div>
                </div>
              </div>
              <div
                v-if="item.questionDescription"
                style="padding-left: 35px; font-size: 12px; color: #ddd"
              >
                {{ item.questionDescription }}
              </div>
              <!-- 单选选择题 -->
              <div v-if="item.questionType == 1">
                <el-radio-group v-removeAriaHidden disabled v-model="item.answerId[0]">
                  <div v-for="(e, index) in item.optionList" :key="index">
                    <div class="flleft">
                      <el-radio :label="e.id" :key="e.id"
                      >{{ e.optionName }}
                      </el-radio>

                      <el-input
                        v-if="
                          item.answerMap[`optionId:${e.id}`] &&
                          e.requiredFlag == 1
                        "
                        disabled
                        :value="
                          item.answerMap[`optionId:${e.id}`]
                            ? item.answerMap[`optionId:${e.id}`].answerContent
                            : '0'
                        "
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                    <div style="padding-left: 40px">
                      <img
                        :src="e.optionPicUrl"
                        alt="加载失败"
                        v-if="e.optionPicUrl"
                        style="width: 40px"
                      />
                    </div>
                  </div>
                </el-radio-group>
              </div>
              <!-- 多选选择题 -->
              <div v-if="item.questionType == 2">
                <div v-for="(e, index) in item.optionList" :key="index">
                  <div class="flleft">
                    <el-checkbox-group disabled v-model="item.answerId">
                      <el-checkbox :label="e.id">
                        {{ e.optionName }}
                      </el-checkbox>
                    </el-checkbox-group>

                    <div :class="e.requiredFlag ? 'required fl mr' : 'fl mr'">
                      <el-input
                        disabled
                        v-if="
                          item.answerMap[`optionId:${e.id}`] &&
                          e.requiredFlag == 1
                        "
                        :value="
                          item.answerMap[`optionId:${e.id}`]
                            ? item.answerMap[`optionId:${e.id}`].answerContent
                            : '0'
                        "
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>

                  <div style="padding-left: 40px">
                    <img
                      :src="e.optionPicUrl"
                      alt="加载失败"
                      v-if="e.optionPicUrl"
                      style="width: 40px"
                    />
                  </div>
                </div>
              </div>
              <!-- 简答题 -->
              <div
                v-if="item.questionType == 4"
                style="margin-left: 20px; margin-top: 10px"
              >
                <el-input
                  disabled
                  type="textarea"
                  size="mini"
                  v-model="
                    item.answerMap[`questionId:${item.id}`].answerContent
                  "
                  placeholder="请输入内容"
                ></el-input>
              </div>
            </div>
          </div>
          <div style="padding-left: 80px">
            <el-button type="primary" @click="backto" style="width: 10%"
            >返回
            </el-button>
          </div>
        </div>
      </card>
      <!-- 富文本图片放大 -->
      <div class="imgDolg" v-show="imgPreview.show">
        <i
          class="el-icon-close"
          id="imgDolgClose"
          @click.stop="imgPreview.show = false"
        ></i>
        <el-image
          ref="imgDolg"
          class="img"
          :src="imgPreview.img"
          fit="cover"
        ></el-image>
      </div>
    </div>
  </backContainer>
</template>

<script>
import {
  Questionmsg,
  AnswerQuestion,
  getServeyanswer
} from '@/api/questions'
import card from '@/components/card.vue'
import { isEmpty, notEmpty } from '@/utils/publicFun'

export default {
  components: { card },
  name: 'MixedStateAdminAnswer',
  data() {
    return {
      id: '',
      surveyName: '',
      anonymousFlag: '',
      surveyDescription: '',
      answerList: [],
      typeList: ['单选题', '多选题', '填空题', '简答题'],
      optionId: [],
      optionId1: [],
      isshow: false,
      answerDuration: 0,
      markStatus: undefined,
      survey: {},
      // 图片放大
      imgPreview: {
        img: '',
        show: false
      }
    }
  },
  created() {
    this.id = this.$route.query.id
    this.userId = this.$route.query.userId
    this.markStatus = this.$route.query.markStatus
    if (this.markStatus == 1) {
      this.getAnswer()
    } else {
      this.getSurvey()
      let that = this
      setInterval(function() {
        that.answerDuration++
      }, 1000)
    }
  },
  mounted() {
  },

  methods: {
    optionIdchange(answerIndex, index) {
      this.answerList[answerIndex].options[index].answerContent = ''
    },
    optionIdradiochange(answerIndex) {
      this.answerList[answerIndex].answerContent = ''
    },
    inputchange() {
      this.$forceUpdate()
    },

    radioClick(answerIndex, e) {
      if (this.answerList[answerIndex].optionId === e.id) {
        this.answerList[answerIndex].optionId = undefined

      } else {
        this.answerList[answerIndex].optionId = e.id
      }
      this.$forceUpdate()
    },
    // 获取问卷
    async getSurvey() {
      let res = await Questionmsg({ surveyId: this.id })
      if (res.data.surveyStatus == 2) {
        this.$modal.msgError('该问卷已停止发放')
        this.$router.go(-1)
        return

      }
      this.surveyName = res.data.surveyName
      this.anonymousFlag = res.data.anonymousFlag
      this.surveyDescription = res.data.surveyDescription
      this.answerList = res.data.questionList.map((i) => {
        if (i.questionType == 3) {
          i.questionNameList = i.questionName
            .split('_______')
            .map((i) => ({ name: i, value: '' }))
        }
        if (i.questionType == 2) {
          i.options = i.optionList.map(() => ({
            optionId: '',
            answerContent: ''
          }))
        }
        return {
          questionId: i.id,
          ...i
        }
      })
    },
    // 获取答卷详情
    getAnswer() {
      getServeyanswer({ surveyId: this.id, userId: this.userId }).then((res) => {
        if (!res.data) {
          this.$modal.msgError('问卷已删除')
          this.$router.go(-1)
        } else {
          this.surveyName = res.data.surveyName
          this.surveyDescription = res.data.surveyDescription
          let arr = res.data.questionList.map((i) => {
            if (i.questionType == 3) {
              i.questionNameList = i.questionName
                .split('_______')
                .map((i) => ({ name: i, value: '' }))
            }
            if (i.questionType == 2) {
              i.options = i.optionList.map(() => ({
                optionId: '',
                answerContent: ''
              }))
            }
            return {
              questionId: i.id,
              ...i
            }
          })
          let replaceArr = []
          for (const arrElement of arr) {
            let item = {
              ...arrElement,
              answerId: []
            }
            //单选
            if (arrElement.questionType == 1) {
              let obj = arrElement.answerMap
              const keys = Object.keys(obj)
              for (const key of keys) {
                if (key.includes('optionId')) {
                  let checkedId = key.slice(9, key.length) - 0
                  item.answerId.push(checkedId)
                }
              }
            }
            //多选
            if (arrElement.questionType == 2) {
              let obj = arrElement.answerMap
              const keys = Object.keys(obj)
              for (const key of keys) {
                if (key.includes('optionId')) {
                  let checkedId = key.slice(9, key.length) - 0
                  item.answerId.push(checkedId)
                }
              }
            }
            replaceArr.push(item)
          }
          this.answerList = replaceArr
        }
      })
    },
    requiredRules() {
      let status = false
      outerloop: for (let index = 0; index < this.answerList.length; index++) {
        let item = this.answerList[index]
        if (item.questionType == 2) {
          for (let n = 0; n < item.optionList.length; n++) {
            let e = item.optionList[n]
            if (
              e.fillFlag == 1 &&
              e.requiredFlag &&
              item.options.find(
                (i) => i.optionId === e.id && isEmpty(i.answerContent)
              )
            ) {
              uni.showToast({
                position: 'top',
                title: `请填写第${index + 1}题中的选项填空`,
                duration: 3000,
                icon: 'none'
              })
              status = true
              break outerloop
            }
          }
        }
        if (item.questionType == 1) {
          for (let n = 0; n < item.optionList.length; n++) {
            let e = item.optionList[n]
            if (
              e.fillFlag == 1 &&
              e.requiredFlag &&
              e.id == item.optionId &&
              isEmpty(item.answerContent)
            ) {
              uni.showToast({
                position: 'top',
                title: `请填写第${index + 1}题中的选项填空`,
                duration: 3000,
                icon: 'none'
              })
              status = true
              break outerloop
            }
          }
        }
        if (item.questionType == 1 && item.requiredFlag == 1) {
          // 单选必填
          if (isEmpty(item.optionId)) {
            this.$message.error(`请回答第${index + 1}题`)
            status = true
            break
          } else {
            // 单选必填并且选择了需要填空的选项
            for (let s = 0; s < item.optionList.length; s++) {
              let o = item.optionList[s]
              if (
                o.fillFlag == 1 &&
                o.requiredFlag &&
                o.id == item.optionId &&
                isEmpty(item.answerContent)
              ) {
                this.$message.error(`请填写第${index + 1}题中的选项填空`)
                status = true
                break outerloop
              }
            }
          }
        } else if (item.questionType == 2 && item.requiredFlag == 1) {
          // 多选题必填
          if (item.options.every((i) => isEmpty(i.optionId))) {
            this.$message.error(`请回答第${index + 1}题`)
            status = true
            break
          } else {
            // 多选必填并且选择了需要填空的选项
            for (let s = 0; s < item.optionList.length; s++) {
              let o = item.optionList[s]
              if (
                o.fillFlag == 1 &&
                o.requiredFlag &&
                item.options.find(
                  (i) => i.optionId === o.id && isEmpty(i.answerContent)
                )
              ) {
                this.$message.error(`请填写第${index + 1}题中的选项填空`)
                status = true
                break outerloop
              }
            }
          }
        } else if (item.questionType == 3 && item.requiredFlag == 1) {
          // 填空题
          let questionState = false
          // 填空题
          for (let i = 0; i < item.questionNameList.length; i++) {
            if (
              i !== item.questionNameList.length - 1 &&
              isEmpty(item.questionNameList[i].value)
            ) {
              questionState = true
              break
            }
          }
          if (questionState) {
            this.$message.error(`请填写第${index + 1}题`)
            status = true
            break
          }
        } else if (
          item.questionType == 4 &&
          item.requiredFlag == 1 &&
          isEmpty(item.answerContent)
        ) {
          // 简答题
          this.$message.error(`请回答第${index + 1}题`)
          status = true
          break
        } else {
          status = false
        }
      }
      return status
    },
    submit() {
      if (this.requiredRules()) {
        return
      }
      let answerList = JSON.parse(JSON.stringify(this.answerList))
      answerList.forEach((i) => {
        if (i.questionType == 3) {
          i.answerContent = JSON.stringify(
            i.questionNameList
              .filter((i) => notEmpty(i.value))
              .map((i) => i.value)
          )
        }
        if (i.questionType == 2) {
          i.options = i.options.filter((i) => !isEmpty(i.optionId))
        }
      })
      AnswerQuestion({
        surveyId: this.id,
        answerDuration: this.answerDuration,
        answerList: answerList
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success(`答卷填写成功`)
          this.$router.go(-1)
        }
      })
    },
    backto() {
      this.$router.go(-1)
    },
    // 图片点击放大
    showImg(e) {
      if (e.target.tagName == 'IMG') {
        this.imgPreview.img = e.target.src
        this.imgPreview.show = true
      }
    }
  }

}
</script>

<style lang="scss" scoped>
::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none !important;
}

.questiontitle {
  border-bottom: 1px dotted #ddd;
  margin: auto;

  .questionname {
    width: 198px;
    margin: auto;
    text-align: center;
    margin-top: 30px;
    color: rgba(39, 196, 120, 1);
    font-size: 18px;
    line-height: 25px;
  }

  .questiontext {
    width: 347px;
    margin: auto;
    margin-bottom: 20px;
    text-align: center;
    margin-top: 30px;
    font-size: 16px;
    line-height: 25px;
  }
}

.computername {
  color: rgba(39, 196, 120, 1);
  font-size: 18px;
  line-height: 28px;
}

.computertext {
  color: #df801f;
  width: 1100px;
  margin-top: 30px;
  margin-bottom: 30px;
  font-size: 16px;
  line-height: 25px;
}

.questions {
  width: 449px;
  margin: auto;
  margin-top: 10px;
}

.computerquestions {
  padding: 30px 60px;
  width: 100%;
  margin: auto;
  margin-top: 10px;
}

.computerquestions > div {
  margin-bottom: 30px;
}

.questioncard {
  height: 100%;
  padding: 40px;
  box-sizing: border-box;
  position: relative;
}

.itemtitle {
  display: flex;
  margin-bottom: 15px;
  align-items: baseline;
}

.computertitle {
  border-bottom: 1px dotted #ddd;
}

.questions > div {
  margin-bottom: 15px;
  border-bottom: 1px dotted #ddd;
}

.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.flleft {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
  margin-left: 20px;
  font-size: 20px;
}

.fl {
  display: flex;

  align-items: center;

  justify-content: flex-start;
}

.mr {
  margin-left: 20px;
}

.center {
  margin: 57px auto 0;
  width: 1190px;
}

.questionitem {
  padding: 20px 0;
  border-bottom: 1px dotted #ddd;
}

.title {
  display: flex;
  font-size: 18px;
  align-items: center;
}

.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.titspace::before {
  content: " ";
  margin-right: 8px;
}

::v-deep p {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

::v-deep p > img {
  margin: 0 15px;
}

.multTitle {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;

  .gapFill {
    display: flex;
    align-items: baseline;
    // flex-wrap: wrap;
  }
}

.textstyle {
  line-height: 100%;
}

//富文本图片放大
.imgDolg {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 9999;
  background-color: rgba(140, 134, 134, 0.6);
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  #imgDolgClose {
    position: fixed;
    top: 35px;
    cursor: pointer;
    right: 7%;
    font-size: 50px;
    color: white;
  }

  .img {
    width: 70%;
    max-height: 90%;
  }
}

.img-hidden {
  width: 0 !important;
  height: 0 !important;
  // visibility:hidden;
}

.submited_text {
  font-size: 18px;
  color: #FFBF6B;
}

.submited_state_top {
  border-radius: 16px 16px 0 0;
  padding: 16px 0;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
}

.bg_color_red {
  background: #fcf1e3;
}
</style>
